package com.sduept.nwld.dataserver.manager.gismap;

import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.extend.LineTower;
import com.sduept.core.ParamManager;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.utils.WebRequestUtil;
import org.jsoup.Connection.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * SuperMap 地图信息Mysql数据库实时更新，当变电站、线路、杆塔等坐标信息变化时 应调用相应的方法
 * 
 * @author laiy
 * @Date 2018年6月15日
 */
//@Service
public class MapGisManager {
	@Autowired
	MapGisElementQueryService mgeqService;
	@Autowired
	MapGisPersistentService mgpService;

	@Autowired
	private ParamManager paramCache;
	@Autowired
	private MapDataCache cimCache;



	/**
	 * 添加单回线路
	 * 
	 * @param lineId
	 * @return
	 * @throws Exception
	 */
	public boolean addSingleLine(String lineId) throws Exception {
		boolean flag = true;
		List<double[]> latlogs = new ArrayList<double[]>();
		List<LineTower> lts = mgeqService.queryLine(1, 0, lineId);
		if (lts != null && !lts.isEmpty()) {
			for (LineTower lineTower : lts) {
				double[] latlog = new double[2];
				latlog[0] = lineTower.getLongitude();
				latlog[1] = lineTower.getLatitude();
				latlogs.add(latlog);
			}
			MapGisUtil.GeoLine genline = MapGisUtil.getSuperMapLineGeoLine(latlogs);
			genline.lineId = lineId;
			genline.lineName = lts.get(0).getLineName();
			genline.loopId = lts.get(0).getLoopCimId();
			genline.loopName = lts.get(0).getLoopCimName();
			flag = mgpService.insertSingleLine(genline);
		} else
			flag = false;

		return flag;
	}

	/**
	 * 编辑单回线路
	 * 
	 * @param lineId
	 * @return
	 * @throws Exception
	 */
	public boolean editSingleLine(String lineId) throws Exception {
		boolean flag = true;
		List<double[]> latlogs = new ArrayList<double[]>();
		List<LineTower> lts = mgeqService.queryLine(1, 0, lineId);
		if (lts != null && !lts.isEmpty()) {
			for (LineTower lineTower : lts) {
				double[] latlog = new double[2];
				latlog[0] = lineTower.getLongitude();
				latlog[1] = lineTower.getLatitude();
				latlogs.add(latlog);
			}
			MapGisUtil.GeoLine genline = MapGisUtil.getSuperMapLineGeoLine(latlogs);
			genline.lineId = lineId;
			genline.lineName = lts.get(0).getLineName();
			genline.loopId = lts.get(0).getLoopCimId();
			genline.loopName = lts.get(0).getLoopCimName();
			flag = mgpService.updateSingleLine(genline);
		} else
			flag = false;

		return flag;
	}

	/**
	 * 删除单回线路
	 * 
	 * @param lineId
	 */
	public boolean delSingleLine(String lineId) throws Exception {
		boolean flag = mgpService.delSingleLine(lineId);
		return flag;
	}

	/**
	 * 添加双回线路
	 * 
	 * @param lineId
	 * @return
	 * @throws Exception
	 */
	public boolean addLoopLine(String lineId) throws Exception {
		boolean flag = true;
		List<double[]> latlogs = new ArrayList<double[]>();
		List<LineTower> lts = mgeqService.queryLine(1, 1, lineId);
		if (lts != null && !lts.isEmpty()) {
			for (LineTower lineTower : lts) {
				double[] latlog = new double[2];
				latlog[0] = lineTower.getLongitude();
				latlog[1] = lineTower.getLatitude();
				latlogs.add(latlog);
			}
			MapGisUtil.GeoLine genline = MapGisUtil.getSuperMapLineGeoLine(latlogs);
			genline.lineId = lineId;
			genline.lineName = lts.get(0).getLineName();
			genline.loopId = lts.get(0).getLoopCimId();
			genline.loopName = lts.get(0).getLoopCimName();
			flag = mgpService.insertLoopLine(genline);
		} else
			flag = false;

		return flag;
	}

	/**
	 * 编辑双回线路
	 * 
	 * @param lineId
	 * @return
	 * @throws Exception
	 */
	public boolean editLoopLine(String lineId) throws Exception {
		boolean flag = true;
		List<double[]> latlogs = new ArrayList<double[]>();
		List<LineTower> lts = mgeqService.queryLine(1, 1, lineId);
		if (lts != null && !lts.isEmpty()) {
			for (LineTower lineTower : lts) {
				double[] latlog = new double[2];
				latlog[0] = lineTower.getLongitude();
				latlog[1] = lineTower.getLatitude();
				latlogs.add(latlog);
			}
			MapGisUtil.GeoLine genline = MapGisUtil.getSuperMapLineGeoLine(latlogs);
			genline.lineId = lineId;
			genline.lineName = lts.get(0).getLineName();
			flag = mgpService.updateLoopLine(genline);
		} else
			flag = false;

		return flag;
	}

	/**
	 * 删除双回线路
	 * 
	 * @param lineId
	 */
	public boolean delLoopLine(String lineId) throws Exception {
		boolean flag = mgpService.delLoopLine(lineId);
		return flag;
	}

	/**
	 * 添加直流线路
	 * 
	 * @param lineId
	 * @return
	 * @throws Exception
	 */
	public boolean addDcLine(String lineId) throws Exception {
		boolean flag = true;
		List<double[]> latlogs = new ArrayList<double[]>();
		TreeSet<LineTower> lts = cimCache.getLtmap500().get(lineId);
		if (lts != null && !lts.isEmpty()) {
			for (LineTower lineTower : lts) {
				double[] latlog = new double[2];
				latlog[0] = lineTower.getLongitude();
				latlog[1] = lineTower.getLatitude();
				latlogs.add(latlog);
			}
			MapGisUtil.GeoLine genline = MapGisUtil.getSuperMapLineGeoLine(latlogs);
			genline.lineId = lineId;
			genline.lineName = lts.first().getLineName();
			flag = mgpService.insertDcLine(genline);
		} else
			flag = false;

		return flag;
	}

	/**
	 * 编辑直流线路
	 * 
	 * @param lineId
	 * @return
	 * @throws Exception
	 */
	public boolean editDcLine(String lineId) throws Exception {
		boolean flag = true;
		List<double[]> latlogs = new ArrayList<double[]>();
		TreeSet<LineTower> lts = cimCache.getLtmap500().get(lineId);
		if (lts != null && !lts.isEmpty()) {
			for (LineTower lineTower : lts) {
				double[] latlog = new double[2];
				latlog[0] = lineTower.getLongitude();
				latlog[1] = lineTower.getLatitude();
				latlogs.add(latlog);
			}
			MapGisUtil.GeoLine genline = MapGisUtil.getSuperMapLineGeoLine(latlogs);
			genline.lineId = lineId;
			genline.lineName = lts.first().getLineName();
			flag = mgpService.updateDcLine(genline);
		} else
			flag = false;

		return flag;
	}

	/**
	 * 删除直流线路
	 * 
	 * @param lineId
	 */
	public boolean delDcLine(String lineId) throws Exception {
		boolean flag = mgpService.delDcLine(lineId);
		return flag;
	}

	/**
	 * 添加单回线路
	 * 
	 * @param lineId
	 * @return
	 * @throws Exception
	 */
	public boolean addNoTowerLine(String lineId) throws Exception {
		boolean flag = true;
		List<double[]> latlogs = new ArrayList<double[]>();
		List<LineTower> lts = mgeqService.queryLine(3, 0, lineId);
		if (lts != null && !lts.isEmpty()) {
			for (LineTower lineTower : lts) {
				double[] latlog = new double[2];
				latlog[0] = lineTower.getLongitude();
				latlog[1] = lineTower.getLatitude();
				latlogs.add(latlog);
			}
			MapGisUtil.GeoLine genline = MapGisUtil.getSuperMapLineGeoLine(latlogs);
			genline.lineId = lineId;
			genline.lineName = lts.get(0).getLineName();
			flag = mgpService.insertNoTowerLine(genline);
		} else
			flag = false;

		return flag;
	}

	/**
	 * 编辑单回线路
	 * 
	 * @param lineId
	 * @return
	 * @throws Exception
	 */
	public boolean editNoTowerLine(String lineId) throws Exception {
		boolean flag = true;
		List<double[]> latlogs = new ArrayList<double[]>();
		List<LineTower> lts = mgeqService.queryLine(3, 0, lineId);
		if (lts != null && !lts.isEmpty()) {
			for (LineTower lineTower : lts) {
				double[] latlog = new double[2];
				latlog[0] = lineTower.getLongitude();
				latlog[1] = lineTower.getLatitude();
				latlogs.add(latlog);
			}
			MapGisUtil.GeoLine genline = MapGisUtil.getSuperMapLineGeoLine(latlogs);
			genline.lineId = lineId;
			genline.lineName = lts.get(0).getLineName();
			flag = mgpService.updateNoTowerLine(genline);
		} else
			flag = false;

		return flag;
	}

	/**
	 * 删除单回线路
	 * 
	 * @param lineId
	 */
	public boolean delNoTowerLine(String lineId) throws Exception {
		boolean flag = mgpService.delNoTowerLine(lineId);
		return flag;
	}

	/**
	 * 添加变电站
	 * 
	 * @param station
	 */
	public boolean addSubStation(Substation station) throws Exception {
		boolean flag = true;
		if (station != null) {
			MapGisUtil.GeoPoint2 geoPoint = new MapGisUtil.GeoPoint2(
					station.getLongitude() != null ? station.getLongitude() : 0,
					station.getLatitude() != null ? station.getLatitude() : 0);
			geoPoint.id = station.getId();
			geoPoint.name = station.getName();
			geoPoint.subControlArea = station.getSubControlArea();
			geoPoint.substationType = station.getSubstationType();
			geoPoint.altitude = Double.toString(station.getAltitude() != null ? station.getAltitude() : 0);
			geoPoint.priority = "\0";
			geoPoint.pasId = station.getRdfId();
			geoPoint.voltageLevel = Float.toString(station.getStandVoltagelevel());
			geoPoint.voltage = Float.toString(station.getActualVoltage());
			geoPoint.flag = "\0";
			flag = mgpService.insertSubStation(geoPoint);

		} else
			flag = false;
		return flag;
	}

	/**
	 * 编辑变电站
	 * 
	 * @param station
	 */
	public boolean editSubStation(Substation station) throws Exception {
		boolean flag = true;
		if (station != null) {
			MapGisUtil.GeoPoint2 geoPoint = new MapGisUtil.GeoPoint2(station.getLongitude(), station.getLatitude());
			geoPoint.name = station.getName();
			geoPoint.subControlArea = station.getSubControlArea();
			geoPoint.substationType = station.getSubstationType();
			geoPoint.altitude = station.getAltitude() == null ? null : Double.toString(station.getAltitude());
			geoPoint.priority = "\0";
			geoPoint.pasId = station.getRdfId();
			geoPoint.voltageLevel = Float.toString(station.getStandVoltagelevel());
			geoPoint.voltage = Float.toString(station.getActualVoltage());
			geoPoint.flag = "\0";
			geoPoint.id = station.getId();
			flag = mgpService.editSubStation(geoPoint);

		} else
			flag = false;
		return flag;
	}

	/**
	 * 删除变电站
	 * 
	 * @param station
	 */
	public boolean deleteSubStation(Substation station) throws Exception {
		boolean flag = true;
		flag = mgpService.delSubStation(station.getId());
		return flag;
	}

	/**
	 * 新增杆塔，会同步更新线路
	 * 
	 * @param lineId
	 * @param towerId
	 */
	public boolean addLineTower(String lineId, String towerId) throws Exception {
		boolean flag = true;
		LineTower lineTower = mgeqService.queryLineTowerById(towerId);
		if (lineTower != null) {
			MapGisUtil.GeoPoint geoPoint = new MapGisUtil.GeoPoint(lineTower.getLongitude(), lineTower.getLatitude());
			geoPoint.id = lineTower.getId();
			geoPoint.name = lineTower.getName();
			geoPoint.lineno = lineTower.getLineno();
			geoPoint.line_cim_id = lineTower.getLineId();
			geoPoint.linename = lineTower.getLineName();
			geoPoint.voltage = Integer.toString(lineTower.getLineVoltage());
			geoPoint.towerserialno = Integer.toString(lineTower.getSerialno());
			geoPoint.isshow = Integer.toString(lineTower.getIsShowInMap());
			geoPoint.sel = Integer.toString(lineTower.getSerialno());
			geoPoint.towerno = lineTower.getTowerno();
			geoPoint.is_loop = Integer.toString(lineTower.getIsLoop());
			geoPoint.loop_cim_id = lineTower.getLoopCimId();
			geoPoint.loopname = lineTower.getLoopCimName();
			flag = mgpService.insertTower(geoPoint);
			if (flag) {
				if (lineTower.getIsLoop() == 0 && lineTower.getIsShowInMap() == 1) {// 单回
					if (mgpService.searchLine(lineId, 0)) {
						flag = editSingleLine(lineId);
					} else {
						flag = addSingleLine(lineId);
					}
				} else if (lineTower.getIsLoop() == 1 && lineTower.getIsShowInMap() == 1) {// 双回
					if (mgpService.searchLine(lineId, 1)) {
						flag = editLoopLine(lineId);
					} else {
						flag = addLoopLine(lineId);
					}
				} else if (lineTower.getIsLoop() == 0 && lineTower.getIsShowInMap() == 3) {// 无杆塔
					if (mgpService.searchLine(lineId, 3)) {
						flag = editNoTowerLine(lineId);
					} else {
						flag = addNoTowerLine(lineId);
					}
				} else if (lineTower.getLineName().contains("直流")) {// 直流
					if (mgpService.searchLine(lineId, 2)) {
						flag = editDcLine(lineId);
					} else {
						flag = addDcLine(lineId);
					}
				}
			} else
				flag = false;
		} else
			flag = false;
		return flag;
	}

	private MapGisUtil.GeoPoint genMGPoint(LineTower lineTower) {
		MapGisUtil.GeoPoint geoPoint = null;
		if (lineTower != null) {
			geoPoint = new MapGisUtil.GeoPoint(lineTower.getLongitude(), lineTower.getLatitude());
			geoPoint.id = lineTower.getId();
			geoPoint.name = lineTower.getName();
			geoPoint.lineno = lineTower.getLineno();
			geoPoint.line_cim_id = lineTower.getLineId();
			geoPoint.linename = lineTower.getLineName();
			geoPoint.voltage = Integer.toString(lineTower.getLineVoltage());
			geoPoint.towerserialno = Integer.toString(lineTower.getSerialno());
			geoPoint.isshow = Integer.toString(lineTower.getIsShowInMap());
			geoPoint.sel = Integer.toString(lineTower.getSerialno());
			geoPoint.towerno = lineTower.getTowerno();
			geoPoint.is_loop = Integer.toString(lineTower.getIsLoop());
			geoPoint.loop_cim_id = lineTower.getLoopCimId();
			geoPoint.loopname = lineTower.getLoopCimName();
		}
		return geoPoint;
	}

	/**
	 * 新增杆塔，会同步更新线路
	 * 
	 * @param lineId
	 */
	public boolean addLineTowers(String lineId, String lineType) throws Exception {
		boolean flag = true;
		TreeSet<LineTower> lineTowers = cimCache.getLtmap500().get(lineId);
		if (lineTowers.size() > 0) {
			LineTower lineTower = lineTowers.first();
			List<MapGisUtil.GeoPoint> geoPoints = new ArrayList<MapGisUtil.GeoPoint>();
			for (LineTower ln : lineTowers) {
				geoPoints.add(genMGPoint(ln));
			}
			flag = mgpService.insertTowers(geoPoints);
			// 要判断线路是单线/双线(回路)/直流/无杆塔(只有两端变电站的线路)
			if (flag) {
				if ("ACLineSegment".equals(lineType)) {
					if (lineTower.getIsLoop() == 0 && lineTower.getIsShowInMap() == 1) {// 单回
						if (mgpService.searchLine(lineId, 0)) {
							flag = editSingleLine(lineId);
						} else {
							flag = addSingleLine(lineId);
						}
					} else if (lineTower.getIsLoop() == 1 && lineTower.getIsShowInMap() == 1) {// 双回
						if (mgpService.searchLine(lineId, 1)) {
							flag = editLoopLine(lineId);
						} else {
							flag = addLoopLine(lineId);
						}
					} else if (lineTower.getIsLoop() == 0 && lineTower.getIsShowInMap() == 3) {// 无杆塔
						if (mgpService.searchLine(lineId, 3)) {
							flag = editNoTowerLine(lineId);
						} else {
							flag = addNoTowerLine(lineId);
						}
					}
				} else if ("DcLinesegment".equals(lineType)) {// 直流
					if (cimCache.getDclineid_map().containsKey(lineId)) {
						if (mgpService.searchLine(lineId, 2)) {
							flag = editDcLine(lineId);
						} else {
							flag = addDcLine(lineId);
						}
					}
				}
			} else
				flag = false;
		}
		return flag;
	}

	/**
	 * 编辑杆塔，会同步更新线路
	 * 
	 * @param lineId
	 * @param towerId
	 */
	public boolean editLineTower(String lineId, String towerId) throws Exception {
		boolean flag = true;
		LineTower lineTower = mgeqService.queryLineTowerById(towerId);
		if (lineTower != null) {
			MapGisUtil.GeoPoint geoPoint = new MapGisUtil.GeoPoint(lineTower.getLongitude(), lineTower.getLatitude());
			geoPoint.id = lineTower.getId();
			geoPoint.name = lineTower.getName();
			geoPoint.lineno = lineTower.getLineno();
			geoPoint.line_cim_id = lineTower.getLineId();
			geoPoint.linename = lineTower.getLineName();
			geoPoint.voltage = Integer.toString(lineTower.getLineVoltage());
			geoPoint.towerserialno = Integer.toString(lineTower.getSerialno());
			geoPoint.isshow = Integer.toString(lineTower.getIsShowInMap());
			geoPoint.sel = Integer.toString(lineTower.getSerialno());
			geoPoint.towerno = lineTower.getTowerno();
			geoPoint.is_loop = Integer.toString(lineTower.getIsLoop());
			geoPoint.loop_cim_id = lineTower.getLoopCimId();
			geoPoint.loopname = lineTower.getLoopCimName();
			flag = mgpService.editTower(geoPoint);
			if (flag) {
				if (lineTower.getIsLoop() == 0 && lineTower.getIsShowInMap() == 1) {// 单回
					if (mgpService.searchLine(lineId, 0)) {
						flag = editSingleLine(lineId);
					} else {
						flag = addSingleLine(lineId);
					}
				} else if (lineTower.getIsLoop() == 1 && lineTower.getIsShowInMap() == 1) {// 双回
					if (mgpService.searchLine(lineId, 1)) {
						flag = editLoopLine(lineId);
					} else {
						flag = addLoopLine(lineId);
					}
				} else if (lineTower.getIsLoop() == 0 && lineTower.getIsShowInMap() == 3) {// 无杆塔
					if (mgpService.searchLine(lineId, 3)) {
						flag = editNoTowerLine(lineId);
					} else {
						flag = addNoTowerLine(lineId);
					}
				} else if (lineTower.getLineName().contains("直流")) {// 直流
					if (mgpService.searchLine(lineId, 2)) {
						flag = editDcLine(lineId);
					} else {
						flag = addDcLine(lineId);
					}
				}
			} else
				flag = false;
		} else
			flag = false;
		return flag;
	}

	/**
	 * 删除杆塔，会同步更新线路
	 * 
	 * @param lineId
	 * @param towerId
	 */
	public boolean deleteLineTower(String lineId, String towerId) throws Exception {
		boolean flag = true;
		LineTower lineTower = mgeqService.queryLineTowerById(towerId);
		if (lineTower != null) {
			flag = mgpService.delTower(lineTower.getId());
			if (flag) {
				if (lineTower.getIsLoop() == 0 && lineTower.getIsShowInMap() == 1) {// 单回
					if (mgpService.searchLine(lineId, 0)) {
						flag = editSingleLine(lineId);
					} else {
						flag = addSingleLine(lineId);
					}
				} else if (lineTower.getIsLoop() == 1 && lineTower.getIsShowInMap() == 1) {// 双回
					if (mgpService.searchLine(lineId, 1)) {
						flag = editLoopLine(lineId);
					} else {
						flag = addLoopLine(lineId);
					}
				} else if (lineTower.getIsLoop() == 0 && lineTower.getIsShowInMap() == 3) {// 无杆塔
					if (mgpService.searchLine(lineId, 3)) {
						flag = editNoTowerLine(lineId);
					} else {
						flag = addNoTowerLine(lineId);
					}
				} else if (lineTower.getLineName().contains("直流")) {// 直流 //不对应该去直流表查询，根据有没有结果判定
					if (mgpService.searchLine(lineId, 2)) {
						flag = editDcLine(lineId);
					} else {
						flag = addDcLine(lineId);
					}
				}
			}
		} else
			flag = false;
		return flag;
	}

	/**
	 * 删除杆塔，会同步更新线路
	 * 
	 * @param lineId
	 */
	public boolean deleteLineTower(String lineId, String lineType, int isloop) throws Exception {
		if (("ACLineSegment".equals(lineType)) && (1 == isloop)) {
			// 删除双回线路
			delLoopLine(lineId);
		} else if (("ACLineSegment".equals(lineType)) && (0 == isloop)) {
			// 删除单回线路
			delSingleLine(lineId);
		} else if ("DcLinesegment".equals(lineType)) {
			delDcLine(lineId);
		}
		return mgpService.delLineTowers(lineId);
	}

	/**
	 * 清除地图缓存
	 * 
	 * @throws Exception
	 */
	public void clearMapCache() throws Exception {
		String mapURL = paramCache.get(ParamDesc.MAP_SERVICE_ADDRESS).getValue();
		// TODO：需要改为可参数配置
		String cacheURl = mapURL + "/clearcache.rjson";
		Map<String, String> requestParams = new HashMap<>();
		requestParams.put("bounds", "{'rightTop':{'y':50,'x':150},'leftBottom':{'y':30,'x':120}}");
		WebRequestUtil.getRequest(cacheURl, Method.GET, requestParams);
	}
}
